﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VAdvantage.Classes;
using VAdvantage.Common;
//using ViennaAdvantage.Process;
//using System.Windows.Forms;
//using ViennaAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.SqlExec;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.Logging;
//using VAdvantage.Controller;
using VAdvantage.Model;
using VAdvantage.Grids;
using System.Windows;


namespace VAdvantage.Model
{
   
    public class CalloutOrderContract : VAdvantage.Model.CalloutEngine
    {
        //	Debug Steps		
        private bool steps = false;

        /// <summary>
        /// Order Header Change - DocType.
        /// - InvoiceRuld/DeliveryRule/PaymentRule
        /// - temporary Document
        ///   Context:
        ///   - DocSubTypeSO
        ///   - HasCharges\
        ///   - (re-sets Business Partner info of required)
        ///            *  @param ctx      
        /// </summary>
        /// <param name="ctx">Context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Model Tab</param>
        /// <param name="mField">Model Field</param>
        /// <param name="value">The new value</param>
        /// <returns>Error message or ""</returns>
        public String DocType(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            String sql = "";
            try
            {
                if (value == DBNull.Value || value == null || value.ToString() == "")
                {
                    return "";
                }
                int C_DocType_ID = System.Convert.ToInt32(value);		//	Actually C_DocTypeTarget_ID
                if (C_DocType_ID == null || C_DocType_ID == 0)
                {
                    return "";
                }
                String oldDocNo;
                if (mTab.GetValue("DocumentNo") == DBNull.Value)
                {
                    oldDocNo = DBNull.Value.ToString();
                }
                else
                {
                    oldDocNo = (String)mTab.GetValue("DocumentNo");
                }
                //	Re-Create new DocNo, if there is a doc number already
                //	and the existing source used a different Sequence number
                //String oldDocNo = (String)mTab.GetValue("DocumentNo");
                //bool newDocNo = (oldDocNo == null);
                bool newDocNo = (oldDocNo == null);
                if (!newDocNo && oldDocNo.StartsWith("<") && oldDocNo.EndsWith(">"))
                    newDocNo = true;
                int oldC_DocType_ID = System.Convert.ToInt32(mTab.GetValue("C_DocType_ID"));

                sql = "SELECT d.DocSubTypeSO,d.HasCharges,'N',"			//	1..3
                     + "d.IsDocNoControlled,s.CurrentNext,s.CurrentNextSys,"     //  4..6
                     + "s.AD_Sequence_ID,d.IsSOTrx, d.IsReturnTrx "              //	7..9
                    /*//jz right outer join
                    + "FROM C_DocType d, AD_Sequence s "
                    + "WHERE C_DocType_ID=?"	//	#1
                    + " AND d.DocNoSequence_ID=s.AD_Sequence_ID(+)"; */
                     + "FROM C_DocType d "
                     + "LEFT OUTER JOIN AD_Sequence s ON (d.DocNoSequence_ID=s.AD_Sequence_ID) "
                     + "WHERE C_DocType_ID=";	//	#1

                int AD_Sequence_ID = 0;
                DataSet ds = new DataSet();
                //	Get old AD_SeqNo for comparison
                if (!newDocNo && oldC_DocType_ID != 0)
                {
                    sql = sql + oldC_DocType_ID;
                    ds = ExecuteQuery.ExecuteDataset(sql, null);
                    //ds.setInt(1, oldC_DocType_ID.intValue());
                    //ResultSet dr = ds.executeQuery();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr = ds.Tables[0].Rows[i];
                        AD_Sequence_ID = Util.GetValueOfInt(dr[5].ToString());
                    }
                }
                else
                {
                    sql = sql + C_DocType_ID;
                    ds = ExecuteQuery.ExecuteDataset(sql, null);
                }
                String DocSubTypeSO = "";
                bool isSOTrx = true;
                bool isReturnTrx = false;
                //	we found document type
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    //	Set Context:	Document Sub Type for Sales Orders
                    DocSubTypeSO = dr[0].ToString();
                    if (DocSubTypeSO == null)
                        DocSubTypeSO = "--";
                    ctx.SetContext(WindowNo, "OrderType", DocSubTypeSO);
                    //	No Drop Ship other than Standard
                    if (!DocSubTypeSO.Equals(MOrder.DocSubTypeSO_Standard))
                        mTab.SetValue("IsDropShip", "N");

                    //	IsSOTrx
                    if ("N".Equals(dr[7].ToString()))
                        isSOTrx = false;

                    //IsReturnTrx
                    isReturnTrx = "Y".Equals(dr[8].ToString());

                    //	Skip these steps for RMA. These are copied from the Original Order
                    if (!isReturnTrx)
                    {
                        if (DocSubTypeSO.Equals(MOrder.DocSubTypeSO_POS))
                            mTab.SetValue("DeliveryRule", X_C_Order.DELIVERYRULE_Force);
                        else if (DocSubTypeSO.Equals(MOrder.DocSubTypeSO_Prepay))
                            mTab.SetValue("DeliveryRule", X_C_Order.DELIVERYRULE_AfterReceipt);
                        else
                            mTab.SetValue("DeliveryRule", X_C_Order.DELIVERYRULE_Availability);

                        //	Invoice Rule
                        if (DocSubTypeSO.Equals(MOrder.DocSubTypeSO_POS)
                            || DocSubTypeSO.Equals(MOrder.DocSubTypeSO_Prepay)
                            || DocSubTypeSO.Equals(MOrder.DocSubTypeSO_OnCredit))
                            mTab.SetValue("InvoiceRule", X_C_Order.INVOICERULE_Immediate);
                        else
                            mTab.SetValue("InvoiceRule", X_C_Order.INVOICERULE_AfterDelivery);

                        //	Payment Rule - POS Order
                        if (DocSubTypeSO.Equals(MOrder.DocSubTypeSO_POS))
                            mTab.SetValue("PaymentRule", X_C_Order.PAYMENTRULE_Cash);
                        else
                            mTab.SetValue("PaymentRule", X_C_Order.PAYMENTRULE_OnCredit);

                        //	Set Context:
                        ctx.SetContext(WindowNo, "HasCharges", dr[1].ToString());
                    }
                    else // Returns
                    {
                        if (DocSubTypeSO.Equals(MOrder.DocSubTypeSO_POS))
                            mTab.SetValue("DeliveryRule", X_C_Order.DELIVERYRULE_Force);
                        else
                            mTab.SetValue("DeliveryRule", X_C_Order.DELIVERYRULE_Manual);
                    }

                    //	DocumentNo
                    if (dr[3].ToString().Equals("Y"))			//	IsDocNoControlled
                    {
                        if (!newDocNo && AD_Sequence_ID != Util.GetValueOfInt(dr[6].ToString()))
                            newDocNo = true;
                        if (newDocNo)
                            try
                            {
                                //if (/*Ini.IsPropertyBool(Ini._COMPIERESYS) &&*/ Envs.GetContext().GetAD_Client_ID() < 1000000)
                                //{
                                //    mTab.SetValue("DocumentNo", "<" + dr[5].ToString() + ">");
                                //}
                                //else
                                //{
                                mTab.SetValue("DocumentNo", "<" + dr[4].ToString() + ">");
                                // }
                            }
                            catch (Exception ex)
                            {

                            }
                    }
                }
                // Skip remaining steps for RMA
                if (isReturnTrx)
                    return "";
                //  When BPartner is changed, the Rules are not set if
                //  it is a POS or Credit Order (i.e. defaults from Standard BPartner)
                //  This re-reads the Rules and applies them.
                if (DocSubTypeSO.Equals(MOrder.DocSubTypeSO_POS) || DocSubTypeSO.Equals(MOrder.DocSubTypeSO_Prepay))    //  not for POS/PrePay
                {

                }
                else
                {
                    int C_BPartner_ID = ctx.GetContextAsInt(WindowNo, "C_BPartner_ID");
                    sql = "SELECT PaymentRule,C_PaymentTerm_ID,"            //  1..2
                        + "InvoiceRule,DeliveryRule,"                       //  3..4
                        + "FreightCostRule,DeliveryViaRule, "               //  5..6
                        + "PaymentRulePO,PO_PaymentTerm_ID "
                        + "FROM C_BPartner "
                        + "WHERE C_BPartner_ID=" + C_BPartner_ID;		//	#1
                    ds = ExecuteQuery.ExecuteDataset(sql, null);
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr = ds.Tables[0].Rows[i];
                        //	PaymentRule
                        String s = dr[isSOTrx ? "PaymentRule" : "PaymentRulePO"].ToString();
                        if (s != null && s.Length != 0)
                        {
                            if (isSOTrx && (s.Equals("B") || s.Equals("S") || s.Equals("U")))           	//	No Cash/Check/Transfer for SO_Trx
                                s = "P";										//  Payment Term
                            if (!isSOTrx && (s.Equals("B")))					//	No Cash for PO_Trx
                                s = "P";										//  Payment Term
                            mTab.SetValue("PaymentRule", s);
                        }
                        //	Payment Term
                        int ii = Util.GetValueOfInt(dr[isSOTrx ? "C_PaymentTerm_ID" : "PO_PaymentTerm_ID"].ToString());
                        //if (!dr.wasNull())
                        if (dr != null)
                        {
                            mTab.SetValue("C_PaymentTerm_ID", ii);
                        }
                        //	InvoiceRule
                        s = dr[2].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("InvoiceRule", s);
                        //	DeliveryRule
                        s = dr[3].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("DeliveryRule", s);
                        //	FreightCostRule
                        s = dr[4].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("FreightCostRule", s);
                        //	DeliveryViaRule
                        s = dr[5].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("DeliveryViaRule", s);
                    }
                }   //  re-read customer rules
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
                return e.Message;

            }

            return "";
        }

        /// <summary>
        /// Order Header - BPartner.
        /// - M_PriceList_ID (+ Context)
        /// - C_BPartner_Location_ID
        /// - Bill_BPartner_ID/Bill_Location_ID
        /// 	- AD_User_ID
        /// 	- POReference
        /// 	- SO_Description
        /// 	- IsDiscountPrinted
        /// 	- InvoiceRule/DeliveryRule/PaymentRule/FreightCost/DeliveryViaRule
        /// 	- C_PaymentTerm_ID
        /// </summary>
        /// <param name="ctx">Context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Model Tab</param>
        /// <param name="mField">Model Field</param>
        /// <param name="value">The new value</param>
        /// <returns>Error message or ""</returns>
        public String BPartner(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            String sql = "";
            try
            {
                if (value == DBNull.Value || value == null || value.ToString() == "")
                {
                    return "";
                }
                int C_BPartner_ID = 0;
                if (value != null)
                    C_BPartner_ID = int.Parse(value.ToString());
                if (C_BPartner_ID == 0)
                    return "";

                // Skip rest of steps for RMA. These fields are copied over from the orignal order instead.
                bool isReturnTrx = (Boolean)mTab.GetValue("IsReturnTrx");
                if (isReturnTrx)
                    return "";

                SetCalloutActive(true);

                sql = "SELECT p.AD_Language,p.C_PaymentTerm_ID,"
                    + " COALESCE(p.M_PriceList_ID,g.M_PriceList_ID) AS M_PriceList_ID, p.PaymentRule,p.POReference,"
                    + " p.SO_Description,p.IsDiscountPrinted,"
                    + " p.InvoiceRule,p.DeliveryRule,p.FreightCostRule,DeliveryViaRule,"
                    + " p.SO_CreditLimit, p.SO_CreditLimit-p.SO_CreditUsed AS CreditAvailable,"
                    + " lship.C_BPartner_Location_ID,c.AD_User_ID,"
                    + " COALESCE(p.PO_PriceList_ID,g.PO_PriceList_ID) AS PO_PriceList_ID, p.PaymentRulePO,p.PO_PaymentTerm_ID,"
                    + " lbill.C_BPartner_Location_ID AS Bill_Location_ID, p.SOCreditStatus, lbill.IsShipTo "
                    + "FROM C_BPartner p"
                    + " INNER JOIN C_BP_Group g ON (p.C_BP_Group_ID=g.C_BP_Group_ID)"
                    + " LEFT OUTER JOIN C_BPartner_Location lbill ON (p.C_BPartner_ID=lbill.C_BPartner_ID AND lbill.IsBillTo='Y' AND lbill.IsActive='Y')"
                    + " LEFT OUTER JOIN C_BPartner_Location lship ON (p.C_BPartner_ID=lship.C_BPartner_ID AND lship.IsShipTo='Y' AND lship.IsActive='Y')"
                    + " LEFT OUTER JOIN AD_User c ON (p.C_BPartner_ID=c.C_BPartner_ID) "
                    + "WHERE p.C_BPartner_ID=" + C_BPartner_ID + " AND p.IsActive='Y'";		//	#1
                bool isSOTrx = ctx.IsSOTrx(WindowNo);

                DataSet ds = ExecuteQuery.ExecuteDataset(sql, null);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    //	PriceList (indirect: IsTaxIncluded & Currency)
                    int ii = Util.GetValueOfInt(dr[isSOTrx ? "M_PriceList_ID" : "PO_PriceList_ID"].ToString());
                    if (dr != null && ii != 0)
                    {
                        mTab.SetValue("M_PriceList_ID", ii);
                    }
                    else
                    {	//	get default PriceList
                        int i1 = ctx.GetContextAsInt("#M_PriceList_ID");
                        if (i1 != 0)
                            mTab.SetValue("M_PriceList_ID", i1);
                    }
                    //	Bill-To BPartner
                    mTab.SetValue("Bill_BPartner_ID", C_BPartner_ID);
                    int bill_Location_ID = Util.GetValueOfInt(dr["Bill_Location_ID"].ToString());
                    if (bill_Location_ID == 0)
                        mTab.SetValue("Bill_Location_ID", null);
                    else
                        mTab.SetValue("Bill_Location_ID", bill_Location_ID);

                    // Ship-To Location
                    int shipTo_ID = Util.GetValueOfInt(dr["C_BPartner_Location_ID"].ToString());
                    //	overwritten by InfoBP selection - works only if InfoWindow
                    //	was used otherwise creates error (uses last value, may belong to differnt BP)
                    if (C_BPartner_ID.ToString().Equals(ctx.GetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_BPartner_ID")))
                    {
                        String loc = ctx.GetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_BPartner_Location_ID");
                        if (loc.Length > 0)
                            shipTo_ID = int.Parse(loc);
                    }
                    if (shipTo_ID == 0)
                        mTab.SetValue("C_BPartner_Location_ID", null);
                    else
                    {
                        mTab.SetValue("C_BPartner_Location_ID", shipTo_ID);
                        if ("Y".Equals(dr["IsShipTo"].ToString()))	//	set the same
                            mTab.SetValue("Bill_Location_ID", shipTo_ID);
                    }
                    //	Contact - overwritten by InfoBP selection
                    int contID = Util.GetValueOfInt(dr["AD_User_ID"].ToString());
                    if (C_BPartner_ID.ToString().Equals(ctx.GetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_BPartner_ID")))
                    {
                        String cont = ctx.GetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "AD_User_ID");
                        if (cont.Length > 0)
                            contID = int.Parse(cont);
                    }
                    if (contID == 0)
                        mTab.SetValue("AD_User_ID", null);
                    else
                    {
                        mTab.SetValue("AD_User_ID", contID);
                        mTab.SetValue("Bill_User_ID", contID);
                    }

                    //	CreditAvailable 
                    if (isSOTrx)
                    {
                        double CreditLimit = Util.GetValueOfDouble(dr["SO_CreditLimit"]);
                        //	String SOCreditStatus = dr.getString("SOCreditStatus");
                        if (CreditLimit != 0)
                        {
                            double CreditAvailable = Util.GetValueOfDouble(dr["CreditAvailable"]);
                            if (dr != null && CreditAvailable < 0)
                            {
                                //mTab.fireDataStatusEEvent("CreditLimitOver",
                                //    DisplayType.getNumberFormat(DisplayType.Amount).format(CreditAvailable),
                                //    false);
                                // MessageBox.Show("Create fireDataStatusEEvent");
                            }
                        }
                    }

                    //	VAdvantage.Model.PO Reference
                    String s = dr["POReference"].ToString();
                    if (s != null && s.Length != 0)
                        mTab.SetValue("POReference", s);
                    // should not be reset to null if we entered already value! VHARCQ, accepted YS makes sense that way
                    // TODO: should get checked and removed if no longer needed!
                    /*else
                        mTab.setValue("POReference", null);*/

                    //	SO Description
                    s = dr["SO_Description"].ToString();
                    if (s != null && s.Trim().Length != 0)
                        mTab.SetValue("Description", s);
                    //	IsDiscountPrinted
                    s = dr["IsDiscountPrinted"].ToString();
                    if (s != null && s.Length != 0)
                        mTab.SetValue("IsDiscountPrinted", s);
                    else
                        mTab.SetValue("IsDiscountPrinted", "N");

                    //	Defaults, if not Walkin Receipt or Walkin Invoice
                    String OrderType = ctx.GetContext(WindowNo, "OrderType");
                    mTab.SetValue("InvoiceRule", X_C_Order.INVOICERULE_AfterDelivery);
                    mTab.SetValue("DeliveryRule", X_C_Order.DELIVERYRULE_Availability);
                    mTab.SetValue("PaymentRule", X_C_Order.PAYMENTRULE_OnCredit);
                    if (OrderType.Equals(MOrder.DocSubTypeSO_Prepay))
                    {
                        mTab.SetValue("InvoiceRule", X_C_Order.INVOICERULE_Immediate);
                        mTab.SetValue("DeliveryRule", X_C_Order.DELIVERYRULE_AfterReceipt);
                    }
                    else if (OrderType.Equals(MOrder.DocSubTypeSO_POS))	//  for POS
                        mTab.SetValue("PaymentRule", X_C_Order.PAYMENTRULE_Cash);
                    else
                    {
                        //	PaymentRule
                        s = dr[isSOTrx ? "PaymentRule" : "PaymentRulePO"].ToString();
                        if (s != null && s.Length != 0)
                        {
                            if (s.Equals("B"))				//	No Cache in Non POS
                                s = "P";
                            if (isSOTrx && (s.Equals("S") || s.Equals("U")))	//	No Check/Transfer for SO_Trx
                                s = "P";										//  Payment Term
                            mTab.SetValue("PaymentRule", s);
                        }
                        //	Payment Term
                        ii = Util.GetValueOfInt(dr[isSOTrx ? "C_PaymentTerm_ID" : "PO_PaymentTerm_ID"].ToString());
                        if (dr != null && ii != 0)//ii=0 when dr return ""
                        {
                            mTab.SetValue("C_PaymentTerm_ID", ii);
                        }
                        //	InvoiceRule
                        s = dr["InvoiceRule"].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("InvoiceRule", s);
                        //	DeliveryRule
                        s = dr["DeliveryRule"].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("DeliveryRule", s);
                        //	FreightCostRule
                        s = dr["FreightCostRule"].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("FreightCostRule", s);
                        //	DeliveryViaRule
                        s = dr["DeliveryViaRule"].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("DeliveryViaRule", s);
                    }
                }
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
                SetCalloutActive(false);
                return e.Message;
            }

            SetCalloutActive(false);
            return "";
        }

        /// <summary>
        /// Order Header - Invoice BPartner.
        /// - M_PriceList_ID (+ Context)
        /// - Bill_Location_ID
        /// - Bill_User_ID
        /// - POReference
        /// - SO_Description
        /// - IsDiscountPrinted
        /// - InvoiceRule/PaymentRule
        /// - C_PaymentTerm_ID
        ///   *  @param ctx      
        /// </summary>
        /// <param name="ctx">Context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Model Tab</param>
        /// <param name="mField">Model Field</param>
        /// <param name="value">The new value</param>
        /// <returns>Error message or ""</returns>
        public String BPartnerBill(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            if (IsCalloutActive())
                return "";
            if (value == DBNull.Value || value == null || value.ToString() == "")
            {
                return "";
            }
            try
            {
                int bill_BPartner_ID = Util.GetValueOfInt(value.ToString());
                if (bill_BPartner_ID == null || bill_BPartner_ID == 0)
                    return "";
                // Skip rest of steps for RMA
                bool isReturnTrx = System.Convert.ToBoolean(mTab.GetValue("IsReturnTrx"));
                if (isReturnTrx)
                    return "";
                String sql = "SELECT p.AD_Language,p.C_PaymentTerm_ID,"
                    + "p.M_PriceList_ID,p.PaymentRule,p.POReference,"
                    + "p.SO_Description,p.IsDiscountPrinted,"
                    + "p.InvoiceRule,p.DeliveryRule,p.FreightCostRule,DeliveryViaRule,"
                    + "p.SO_CreditLimit, p.SO_CreditLimit-p.SO_CreditUsed AS CreditAvailable,"
                    + "c.AD_User_ID,"
                    + "p.PO_PriceList_ID, p.PaymentRulePO, p.PO_PaymentTerm_ID,"
                    + "lbill.C_BPartner_Location_ID AS Bill_Location_ID "
                    + "FROM C_BPartner p"
                    + " LEFT OUTER JOIN C_BPartner_Location lbill ON (p.C_BPartner_ID=lbill.C_BPartner_ID AND lbill.IsBillTo='Y' AND lbill.IsActive='Y')"
                    + " LEFT OUTER JOIN AD_User c ON (p.C_BPartner_ID=c.C_BPartner_ID) "
                    + "WHERE p.C_BPartner_ID=" + bill_BPartner_ID + " AND p.IsActive='Y'";		//	#1
                bool isSOTrx = "Y".Equals(ctx.GetContext(WindowNo, "IsSOTrx"));

                DataSet ds = ExecuteQuery.ExecuteDataset(sql, null);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    //	PriceList (indirect: IsTaxIncluded & Currency)
                    int ii = Util.GetValueOfInt(dr[isSOTrx ? "M_PriceList_ID" : "PO_PriceList_ID"].ToString());
                    if (dr != null)
                        mTab.SetValue("M_PriceList_ID", ii);
                    else
                    {	//	get default PriceList
                        int iCont = ctx.GetContextAsInt("#M_PriceList_ID");
                        if (iCont != 0)
                            mTab.SetValue("M_PriceList_ID", Util.GetValueOfInt(iCont.ToString()));
                    }
                    int bill_Location_ID = Util.GetValueOfInt(dr["Bill_Location_ID"].ToString());
                    //	overwritten by InfoBP selection - works only if InfoWindow
                    //	was used otherwise creates error (uses last value, may belong to differnt BP)
                    if (bill_BPartner_ID.ToString().Equals(ctx.GetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_BPartner_ID")))
                    {
                        String loc = ctx.GetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_BPartner_Location_ID");
                        if (loc.Length > 0)
                            bill_Location_ID = Util.GetValueOfInt(loc);
                    }
                    if (bill_Location_ID == 0)
                        mTab.SetValue("Bill_Location_ID", null);
                    else
                        mTab.SetValue("Bill_Location_ID", Util.GetValueOfInt(bill_Location_ID.ToString()));

                    //	Contact - overwritten by InfoBP selection
                    int contID = Util.GetValueOfInt(dr["AD_User_ID"].ToString());
                    if (bill_BPartner_ID.ToString().Equals(ctx.GetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "C_BPartner_ID")))
                    {
                        String cont = ctx.GetContext(Envs.WINDOW_INFO, Envs.TAB_INFO, "AD_User_ID");
                        if (cont.Length > 0)
                            contID = Util.GetValueOfInt(cont);
                    }
                    if (contID == 0)
                        mTab.SetValue("Bill_User_ID", null);
                    else
                        mTab.SetValue("Bill_User_ID", Util.GetValueOfInt(contID.ToString()));
                    //	CreditAvailable 
                    if (isSOTrx)
                    {
                        double CreditLimit = Util.GetValueOfDouble(dr["SO_CreditLimit"]);
                        if (CreditLimit != 0)
                        {
                            double CreditAvailable = Util.GetValueOfDouble(dr["CreditAvailable"]);
                            if (dr != null && CreditAvailable < 0)
                            {
                                //mTab.fireDataStatusEEvent("CreditLimitOver",
                                //    DisplayType.getNumberFormat(DisplayType.Amount).format(CreditAvailable),
                                //    false);
                                // MessageBox.Show("second msg to create fireDataStatusEEvent");
                            }
                        }
                    }

                    //	VAdvantage.Model.PO Reference
                    String s = dr["POReference"].ToString();

                    // Order Reference should not be set by Bill To BPartner; only by BPartner.
                    /* if (s != null && s.length() != 0)
                        mTab.setValue("POReference", s);
                    else
                        mTab.setValue("POReference", null);*/
                    //	SO Description
                    s = dr["SO_Description"].ToString();
                    if (s != null && s.Trim().Length != 0)
                        mTab.SetValue("Description", s);
                    //	IsDiscountPrinted
                    s = dr["IsDiscountPrinted"].ToString();
                    if (s != null && s.Length != 0)
                        mTab.SetValue("IsDiscountPrinted", s);
                    else
                        mTab.SetValue("IsDiscountPrinted", "N");

                    //	Defaults, if not Walkin Receipt or Walkin Invoice
                    String OrderType = ctx.GetContext(WindowNo, "OrderType");
                    mTab.SetValue("InvoiceRule", X_C_Order.INVOICERULE_AfterDelivery);
                    mTab.SetValue("PaymentRule", X_C_Order.PAYMENTRULE_OnCredit);
                    if (OrderType.Equals(MOrder.DocSubTypeSO_Prepay))
                        mTab.SetValue("InvoiceRule", X_C_Order.INVOICERULE_Immediate);
                    else if (OrderType.Equals(MOrder.DocSubTypeSO_POS))	//  for POS
                        mTab.SetValue("PaymentRule", X_C_Order.PAYMENTRULE_Cash);
                    else
                    {
                        //	PaymentRule
                        s = dr[isSOTrx ? "PaymentRule" : "PaymentRulePO"].ToString();
                        if (s != null && s.Length != 0)
                        {
                            if (s.Equals("B"))				//	No Cache in Non POS
                                s = "P";
                            if (isSOTrx && (s.Equals("S") || s.Equals("U")))	//	No Check/Transfer for SO_Trx
                                s = "P";										//  Payment Term
                            mTab.SetValue("PaymentRule", s);
                        }
                        //	Payment Term
                        ii = Util.GetValueOfInt(dr[isSOTrx ? "C_PaymentTerm_ID" : "PO_PaymentTerm_ID"].ToString());
                        if (dr != null)
                            mTab.SetValue("C_PaymentTerm_ID", ii);
                        //	InvoiceRule
                        s = dr["InvoiceRule"].ToString();
                        if (s != null && s.Length != 0)
                            mTab.SetValue("InvoiceRule", s);
                    }
                }
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "bPartnerBill", e);
                return e.Message;
                return "";
            }
            return "";
        }

        /// <summary>
        /// Order Header - PriceList.
        /// (used also in Invoice)
        /// - C_Currency_ID
        /// 	- IsTaxIncluded
        /// 	Window Context:
        /// 	- EnforcePriceLimit
        /// 	- StdPrecision
        /// 	- M_PriceList_Version_ID
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>null or error message</returns>
        public String PriceList(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            String sql = "";
            try
            {
                if (value == DBNull.Value || value == null || value.ToString() == "")
                {
                    return "";
                }
                int M_PriceList_ID = Util.GetValueOfInt(value.ToString());
                if (M_PriceList_ID == null || M_PriceList_ID == 0)
                    return "";
                if (steps)
                {
                    log.Warning("init");
                }

                sql = "SELECT pl.IsTaxIncluded,pl.EnforcePriceLimit,pl.C_Currency_ID,c.StdPrecision,"
                    + "plv.M_PriceList_Version_ID,plv.ValidFrom "
                    + "FROM M_PriceList pl,C_Currency c,M_PriceList_Version plv "
                    + "WHERE pl.C_Currency_ID=c.C_Currency_ID"
                    + " AND pl.M_PriceList_ID=plv.M_PriceList_ID"
                    + " AND pl.M_PriceList_ID=" + M_PriceList_ID						//	1
                    + "ORDER BY plv.ValidFrom DESC";
                //	Use newest price list - may not be future

                DataSet ds = ExecuteQuery.ExecuteDataset(sql, null);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    //	Tax Included
                    mTab.SetValue("IsTaxIncluded", (Boolean)("Y".Equals(dr[0].ToString())));
                    //	Price Limit Enforce
                    ctx.SetContext(WindowNo, "EnforcePriceLimit", dr[1].ToString());
                    //	Currency
                    int ii = Util.GetValueOfInt(dr[2].ToString());
                    mTab.SetValue("C_Currency_ID", ii);
                    int prislst = Util.GetValueOfInt(dr[4].ToString());
                    //	PriceList Version
                    ctx.SetContext(WindowNo, "M_PriceList_Version_ID", prislst);
                }
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
                //return e.Message;
                // MessageBox.Show("Callout--PriceList");
            }
            if (steps)
            {
                log.Warning("fini");
            }
            return "";
        }

        /// <summary>
        /// Order Line - Product.
        /// - reset C_Charge_ID / M_AttributeSetInstance_ID
        /// - PriceList, PriceStd, PriceLimit, C_Currency_ID, EnforcePriceLimit
        /// - UOM
        /// Calls Tax
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>null or error message</returns>
        public String Product(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            if (value == DBNull.Value || value == null || value.ToString() == "")
            {
                return "";
            }
            try
            {  ///
                // Boolean flag1 = System.Convert.ToBoolean(value);
                //// Int32 M_Product_ID = 0;
                // string ProductType = "";
                int M_Product_ID = System.Convert.ToInt32(value);

                // if (flag1 == null)
                // {
                //     return "";
                // }
                // if (flag1 == true)
                // {

                //     M_Product_ID = Util.GetValueOfInt(mTab.GetValue("M_Product_ID"));
                //     String sql = "select producttype from m_product where m_product_id=" + M_Product_ID + "";
                //     ProductType = VAdvantage.Utility.Util.GetValueOfString(DB.ExecuteScalar(sql, null, null));

                //     if (ProductType == "S")
                //     {
                //         mTab.SetValue("IsChecked", false);
                //         return "";

                //}
                //else
                //{
                //    mTab.SetValue("IsChecked", true);
                //    //return "Please Select Product Having ProductType Service";

                //}

                //}
                //else
                //{

                //}
                ///

                if (M_Product_ID == null || M_Product_ID == 0)
                    return "";

                bool isReturnTrx = "Y".Equals(ctx.GetContext(WindowNo, "IsReturnTrx"));
                if (isReturnTrx)
                    return "";

                SetCalloutActive(true);
                if (steps)
                {
                    log.Warning("init");
                }
                //
                mTab.SetValue("C_Charge_ID", null);
                //	Set Attribute
                if (ctx.GetContextAsInt(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_Product_ID") == M_Product_ID
                    && ctx.GetContextAsInt(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_AttributeSetInstance_ID") != 0)
                {
                    mTab.SetValue("M_AttributeSetInstance_ID", System.Convert.ToInt32(ctx.GetContextAsInt(Envs.WINDOW_INFO, Envs.TAB_INFO, "M_AttributeSetInstance_ID")));
                }
                else
                {
                    mTab.SetValue("M_AttributeSetInstance_ID", null);
                }

                /*****	Price Calculation see also qty	****/
                int C_BPartner_ID = ctx.GetContextAsInt(WindowNo, "C_BPartner_ID");
                Decimal Qty = Util.GetValueOfDecimal(mTab.GetValue("QtyEntered"));
                bool isSOTrx = ctx.GetContext(WindowNo, "IsSOTrx").Equals("Y");
                MProductPricing pp = new MProductPricing(ctx.GetAD_Client_ID(), ctx.GetAD_Org_ID(),
                        M_Product_ID, C_BPartner_ID, Qty, isSOTrx);
                int M_PriceList_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_ID");
                pp.SetM_PriceList_ID(M_PriceList_ID);
                /** PLV is only accurate if PL selected in header */
                int M_PriceList_Version_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_Version_ID");
                pp.SetM_PriceList_Version_ID(M_PriceList_Version_ID);
                DateTime orderDate = System.Convert.ToDateTime(mTab.GetValue("DateOrdered"));
                pp.SetPriceDate(orderDate);
                //		
                mTab.SetValue("PriceList", pp.GetPriceList());
                mTab.SetValue("PriceLimit", pp.GetPriceLimit());
                mTab.SetValue("PriceActual", pp.GetPriceStd());
                mTab.SetValue("PriceEntered", pp.GetPriceStd());
                mTab.SetValue("C_Currency_ID", System.Convert.ToInt32(pp.GetC_Currency_ID()));
                mTab.SetValue("Discount", pp.GetDiscount());
                mTab.SetValue("C_UOM_ID", System.Convert.ToInt32(pp.GetC_UOM_ID()));
                mTab.SetValue("QtyEntered", mTab.GetValue("QtyEntered"));
                ctx.SetContext(WindowNo, "EnforcePriceLimit", pp.IsEnforcePriceLimit() ? "Y" : "N");
                ctx.SetContext(WindowNo, "DiscountSchema", pp.IsDiscountSchema() ? "Y" : "N");

                //	Check/Update Warehouse Setting
                //	int M_Warehouse_ID = ctx.getContextAsInt( Envs.WINDOW_INFO, "M_Warehouse_ID");
                //	int wh = (int)mTab.getValue("M_Warehouse_ID");
                //	if (wh.intValue() != M_Warehouse_ID)
                //	{
                //		mTab.setValue("M_Warehouse_ID", new int(M_Warehouse_ID));
                //		ADialog.warn(,WindowNo, "WarehouseChanged");
                //	}

                if (ctx.IsSOTrx(WindowNo))
                {
                    MProduct product = MProduct.Get(ctx, M_Product_ID);
                    if (product.IsStocked())
                    {
                        Decimal QtyEntered = Util.GetValueOfDecimal(mTab.GetValue("QtyEntered"));
                        int M_Warehouse_ID = ctx.GetContextAsInt(WindowNo, "M_Warehouse_ID");
                        int M_AttributeSetInstance_ID = ctx.GetContextAsInt(WindowNo, "M_AttributeSetInstance_ID");
                        Decimal? available = MStorage.GetQtyAvailable(M_Warehouse_ID, M_Product_ID, M_AttributeSetInstance_ID, null);
                        if (available == null)
                            available = Envs.ZERO;
                        if (available == 0)
                        {
                            //mTab.fireDataStatusEEvent("NoQtyAvailable", "0", false);
                          //  ShowMessage.Info("NoQtyAvailable", true, "0", "");
                        }
                        else if (available.Value.CompareTo(QtyEntered) < 0)
                        {
                            //mTab.fireDataStatusEEvent("InsufficientQtyAvailable", available.toString(), false);
                          //  ShowMessage.Info("InsufficientQtyAvailable", true, available.ToString(), "");
                        }
                        else
                        {
                            int C_OrderLine_ID = 0;
                            if (mTab.GetValue("C_OrderLine_ID") != DBNull.Value)
                            {
                                C_OrderLine_ID = System.Convert.ToInt32(mTab.GetValue("C_OrderLine_ID"));
                            }

                            if (C_OrderLine_ID == null)
                                C_OrderLine_ID = 0;
                            Decimal notReserved = MOrderLine.GetNotReserved(ctx,
                                M_Warehouse_ID, M_Product_ID, M_AttributeSetInstance_ID,
                                C_OrderLine_ID);
                            if (notReserved == null)
                                notReserved = Envs.ZERO;
                            //Decimal total = available.subtract(notReserved);
                            Decimal total = Decimal.Subtract(available.Value, notReserved);
                            if (total.CompareTo(QtyEntered) < 0)
                            {
                                String info = Msg.ParseTranslation(ctx, "@QtyAvailable@=" + available
                                    + " - @QtyNotReserved@=" + notReserved + " = " + total);
                                //mTab.fireDataStatusEEvent("InsufficientQtyAvailable",info, false);
                                ShowMessage.Info("InsufficientQtyAvailable", true, info, "");
                            }
                        }
                    }
                }
                SetCalloutActive(false);

                if (steps)
                {
                    log.Warning("fini");
                }
            }
            catch
            {
                // MessageBox.Show("error in Product");
            }

            return Tax(ctx, WindowNo, mTab, mField, value);
        }

        /// <summary>
        /// Order Line - Charge.
        /// - updates PriceActual from Charge
        /// - sets PriceLimit, PriceList to zero
        /// 	Calles tax
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value"> New Value</param>
        /// <returns>null or error message</returns>
        public String Charge(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            try
            {
                if (value == DBNull.Value || value == null || value.ToString() == "")
                {
                    return "";
                }

                int C_Charge_ID = System.Convert.ToInt32(value);
                if (C_Charge_ID == null || C_Charge_ID == 0)
                    return "";

                bool isReturnTrx = "Y".Equals(ctx.GetContext("IsReturnTrx"));
                if (isReturnTrx)
                    return "";

                //	No Product defined
                if (mTab.GetValue("M_Product_ID") != null && mTab.GetValue("M_Product_ID") != DBNull.Value)
                {
                    mTab.SetValue("C_Charge_ID", null);
                    return "ChargeExclusively";
                }
                mTab.SetValue("M_AttributeSetInstance_ID", null);
                mTab.SetValue("S_ResourceAssignment_ID", null);
                mTab.SetValue("C_UOM_ID", 100);	//	EA

                ctx.SetContext(WindowNo, "DiscountSchema", "N");
                String sql = "SELECT ChargeAmt FROM C_Charge WHERE C_Charge_ID=" + C_Charge_ID;
                try
                {
                    DataSet ds = ExecuteQuery.ExecuteDataset(sql, null);
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr = ds.Tables[0].Rows[i];
                        mTab.SetValue("PriceEntered", Util.GetValueOfDecimal(dr[0]));
                        mTab.SetValue("PriceActual", Util.GetValueOfDecimal(dr[0]));
                        mTab.SetValue("PriceLimit", Envs.ZERO);
                        mTab.SetValue("PriceList", Envs.ZERO);
                        mTab.SetValue("Discount", Envs.ZERO);
                    }
                }
                catch (Exception e)
                {
                    log.Log(Level.SEVERE, sql, e);
                    //return e.Message;
                }
            }
            catch (Exception ex)
            {
                // MessageBox.Show("error in Charge");
            }
            return Tax(ctx, WindowNo, mTab, mField, value);
        }

        /// <summary>
        /// Order Line - Tax.
        /// - basis: Product, Charge, BPartner Location
        /// 	- sets C_Tax_ID
        /// 	Calles Amount
        /// 	@param ctx 
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>ull or error message</returns>
    


        /// <summary>
        /// Order Line - Amount.
        /// - called from QtyEntered, Discount and PriceActual
        /// - calculates Discount or Actual Amount
        /// - calculates LineNetAmt
        /// - enforces PriceLimit
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>null or error message</returns>
        /// 
        public String Tax(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            //if (value == DBNull.Value || value == null || value.ToString() == "")
            //{
            //    return "";
            //}
            Int32 C_Tax_ID = 0;
            Decimal Rate = Envs.ZERO;
            Decimal TotalRate = Envs.ZERO;
            String LineAmount = "";
            //Decimal GrandTotal = Envs.ZERO;
            //Decimal Discount=Envs.ZERO;
            //Decimal taxamt = Envs.ZERO;
            C_Tax_ID = VAdvantage.Utility.Util.GetValueOfInt(mTab.GetValue("C_Tax_ID"));
            String sqltax = "select rate from c_tax WHERE c_tax_id=" + C_Tax_ID + "";
            Rate = VAdvantage.Utility.Util.GetValueOfDecimal(DB.ExecuteScalar(sqltax, null, null));
            LineAmount=Amt(ctx, WindowNo, mTab, mField, value);
            Decimal LineNetAmt = Util.GetValueOfDecimal(mTab.GetValue("LineNetAmt"));
            TotalRate = Util.GetValueOfDecimal((Util.GetValueOfDecimal(LineNetAmt) * Util.GetValueOfDecimal(Rate)) / 100);
           // taxamt = Util.GetValueOfDecimal(mTab.SetValue("TaxAmt", TotalRate));
            //Discount=VAdvantage.Utility.Util.GetValueOfDecimal(mTab.GetValue("Discount"));
            mTab.SetValue("taxamt", TotalRate);

            

            //GrandTotal = Util.GetValueOfDecimal(LineNetAmt) + Util.GetValueOfDecimal(TotalRate);
            //mTab.SetValue("GrandTotal",GrandTotal);
            //try
            //{
            //    String column = mField.GetColumnName();
            //    if (value == null)
            //        return "";
            //    if   (steps)
            //    {
            //        log.Warning("init");
            //    }
            //    //	Check Product
            //    int M_Product_ID = 0;
            //    if (column.Equals("M_Product_ID"))
            //    {
            //        M_Product_ID = System.Convert.ToInt32(value);
            //    }
            //    else
            //    {
            //        M_Product_ID = System.Convert.ToInt32(ctx.GetContextAsInt(WindowNo, "M_Product_ID"));
            //    }
            //    int C_Charge_ID = 0;
            //    if (column.Equals("C_Charge_ID"))
            //    {
            //        C_Charge_ID = System.Convert.ToInt32(value);
            //    }
            //    else
            //    {
            //        C_Charge_ID = System.Convert.ToInt32(ctx.GetContextAsInt(WindowNo, "C_Charge_ID"));
            //    }
            //    log.Fine("Product=" + M_Product_ID + ", C_Charge_ID=" + C_Charge_ID);
            //    if (M_Product_ID == 0 && C_Charge_ID == 0)
            //    {
            //        return Amt(ctx, WindowNo, mTab, mField, value);		//
            //    }
            //    //	Check Partner Location
            //    int shipC_BPartner_Location_ID = 0;
            //    if (column.Equals("C_BPartner_Location_ID"))
            //    {
            //        shipC_BPartner_Location_ID = System.Convert.ToInt32(value);
            //    }
            //    else
            //    {
            //        shipC_BPartner_Location_ID = System.Convert.ToInt32(ctx.GetContextAsInt(WindowNo, "C_BPartner_Location_ID"));
            //    }
            //    if (shipC_BPartner_Location_ID == 0)
            //    {
            //        return Amt(ctx, WindowNo, mTab, mField, value);		//
            //    }
            //    log.Fine("Ship BP_Location=" + shipC_BPartner_Location_ID);
            //    //DateTime billDate = CommonFunctions.CovertMilliToDate(ctx.GetContextAsTime(WindowNo, "DateOrdered"));
            //    DateTime billDate = System.Convert.ToDateTime(ctx.GetContext(WindowNo, "DateOrdered", false));
            //    log.Fine("Bill Date=" + billDate);
            //    //DateTime shipDate = CommonFunctions.CovertMilliToDate(ctx.GetContextAsTime(WindowNo, "DatePromised"));
            //    DateTime shipDate = System.Convert.ToDateTime(ctx.GetContext(WindowNo, "DatePromised", false));
            //    log.Fine("Ship Date=" + shipDate);
            //    int AD_Org_ID = ctx.GetContextAsInt(WindowNo, "AD_Org_ID");
            //    log.Fine("Org=" + AD_Org_ID);
            //    int M_Warehouse_ID = ctx.GetContextAsInt(WindowNo, "M_Warehouse_ID");
            //    log.Fine("Warehouse=" + M_Warehouse_ID);
            //    int billC_BPartner_Location_ID = ctx.GetContextAsInt(WindowNo, "Bill_Location_ID");
            //    if (billC_BPartner_Location_ID == 0)
            //        billC_BPartner_Location_ID = shipC_BPartner_Location_ID;
            //    log.Fine("Bill BP_Location=" + billC_BPartner_Location_ID);
            //    int C_Tax_ID = VAdvantage.Model.Tax.Get(ctx, M_Product_ID, C_Charge_ID, billDate, shipDate,
            //        AD_Org_ID, M_Warehouse_ID, billC_BPartner_Location_ID, shipC_BPartner_Location_ID,
            //        "Y".Equals(ctx.GetContext(WindowNo, "IsSOTrx")));
            //    log.Info("Tax ID=" + C_Tax_ID);
            //    //
            //    if (C_Tax_ID == 0)
            //    {
            //        //mTab.fireDataStatusEEvent(CLogger.retrieveError());
            //        ShowMessage.Info(VLogger.RetrieveError().ToString(), true, "", "");
            //    }
            //    else
            //    {
            //        mTab.SetValue("C_Tax_ID", System.Convert.ToInt32(C_Tax_ID));
            //    }
            //    //
            //    if (steps)
            //    {
            //        log.Warning("fini");
            //    }
            //}
            //catch (Exception ex)
            //{
            //    // MessageBox.Show("error in Tax");
            //}
            return Amt(ctx, WindowNo, mTab, mField, value);
        }

    

        public String Amt(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            if (IsCalloutActive() || value == null || value.ToString() == "" || value == DBNull.Value)
            {
                return "";
            }
            SetCalloutActive(true);
            try
            {

                if (steps)
                {
                    log.Warning("init");
                }
                
                int C_UOM_To_ID = ctx.GetContextAsInt(WindowNo, "C_UOM_ID");
                int M_Product_ID = ctx.GetContextAsInt(WindowNo, "M_Product_ID");
                int M_PriceList_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_ID");
                int StdPrecision = MPriceList.GetPricePrecision(ctx, M_PriceList_ID);
                Decimal? QtyEntered, PriceEntered, PriceActual, PriceLimit, Discount, PriceList;
                //	get values
                QtyEntered = Util.GetValueOfDecimal(mTab.GetValue("QtyEntered"));
                QtyEntered = Util.GetValueOfDecimal(mTab.GetValue("QtyEntered"));
                log.Fine("QtyEntered=" + QtyEntered + ", Ordered=" + QtyEntered + ", UOM=" + C_UOM_To_ID);
                //
                PriceEntered = Util.GetValueOfDecimal(mTab.GetValue("PriceEntered"));
                PriceActual = Util.GetValueOfDecimal(mTab.GetValue("PriceActual"));

                Discount = Util.GetValueOfDecimal(mTab.GetValue("Discount"));
                PriceLimit = Util.GetValueOfDecimal(mTab.GetValue("PriceLimit"));
                PriceList = Util.GetValueOfDecimal(mTab.GetValue("PriceList"));
                log.Fine("PriceList=" + PriceList + ", Limit=" + PriceLimit + ", Precision=" + StdPrecision);
                log.Fine("PriceEntered=" + PriceEntered + ", Actual=" + PriceActual + ", Discount=" + Discount);

                //	Qty changed - recalc price
                if ((mField.GetColumnName().Equals("QtyEntered")
                    || mField.GetColumnName().Equals("QtyEntered")
                    || mField.GetColumnName().Equals("M_Product_ID"))
                    && !"N".Equals(ctx.GetContext(WindowNo, "DiscountSchema")))
                {
                    int C_BPartner_ID = ctx.GetContextAsInt(WindowNo, "C_BPartner_ID");
                    if (mField.GetColumnName().Equals("QtyEntered"))
                        QtyEntered = (Decimal?)MUOMConversion.ConvertProductTo(ctx, M_Product_ID,
                            C_UOM_To_ID, QtyEntered);
                    if (QtyEntered == null)
                    {

                    }
                      //  QtyEntered = QtyEntered;
                    bool isSOTrx = ctx.GetContext(WindowNo, "IsSOTrx").Equals("Y");
                    MProductPricing pp = new MProductPricing(ctx.GetAD_Client_ID(), ctx.GetAD_Org_ID(),
                            M_Product_ID, C_BPartner_ID, QtyEntered, isSOTrx);
                    pp.SetM_PriceList_ID(M_PriceList_ID);
                    int M_PriceList_Version_ID = ctx.GetContextAsInt(WindowNo, "M_PriceList_Version_ID");
                    pp.SetM_PriceList_Version_ID(M_PriceList_Version_ID);
                    DateTime date = System.Convert.ToDateTime(mTab.GetValue("DateOrdered"));
                    pp.SetPriceDate(date);
                    //
                    PriceEntered = (Decimal?)MUOMConversion.ConvertProductFrom(ctx, M_Product_ID,
                        C_UOM_To_ID, pp.GetPriceStd());
                    if (PriceEntered == null)
                        PriceEntered = pp.GetPriceStd();
                    //
                    log.Fine("QtyChanged -> PriceActual=" + pp.GetPriceStd()
                        + ", PriceEntered=" + PriceEntered + ", Discount=" + pp.GetDiscount());
                    PriceActual = pp.GetPriceStd();
                    mTab.SetValue("PriceActual", PriceActual);
                    mTab.SetValue("Discount", pp.GetDiscount());
                    mTab.SetValue("PriceEntered", PriceEntered);
                    ctx.SetContext(WindowNo, "DiscountSchema", pp.IsDiscountSchema() ? "Y" : "N");
                }
                else if (mField.GetColumnName().Equals("PriceActual"))
                {
                    PriceActual = Util.GetValueOfDecimal(value);
                    PriceEntered = (Decimal?)MUOMConversion.ConvertProductFrom(ctx, M_Product_ID,
                        C_UOM_To_ID, PriceActual.Value);
                    if (PriceEntered == null)
                        PriceEntered = PriceActual;
                    //
                    log.Fine("PriceActual=" + PriceActual
                        + " -> PriceEntered=" + PriceEntered);
                    mTab.SetValue("PriceEntered", PriceEntered);
                }
                else if (mField.GetColumnName().Equals("PriceEntered"))
                {
                    PriceEntered = Util.GetValueOfDecimal(value);
                    PriceActual = (Decimal?)MUOMConversion.ConvertProductTo(ctx, M_Product_ID,
                        C_UOM_To_ID, PriceEntered);
                    if (PriceActual == null)
                        PriceActual = PriceEntered;
                    //
                    log.Fine("PriceEntered=" + PriceEntered
                        + " -> PriceActual=" + PriceActual);
                    mTab.SetValue("PriceActual", PriceActual);
                }

                //  Discount entered - Calculate Actual/Entered
                if (mField.GetColumnName().Equals("Discount"))
                {
                    PriceActual = Util.GetValueOfDecimal(((100.0 - Decimal.ToDouble(Discount.Value))
                        / 100.0 * Decimal.ToDouble(PriceList.Value)));
                    if (Envs.Scale(PriceActual.Value) > StdPrecision)
                        PriceActual = Decimal.Round(PriceActual.Value, StdPrecision);//);//, MidpointRounding.AwayFromZero);

                    PriceEntered = (Decimal?)MUOMConversion.ConvertProductFrom(ctx, M_Product_ID,
                        C_UOM_To_ID, PriceActual.Value);
                    if (PriceEntered == null)
                        PriceEntered = PriceActual;
                    mTab.SetValue("PriceActual", PriceActual);
                    mTab.SetValue("PriceEntered", PriceEntered);
                }
                //	calculate Discount
                else
                {
                    if (PriceList == 0)
                    {
                        Discount = Envs.ZERO;
                    }
                    else
                    {
                        //Discount = new BigDecimal ((PriceList.doubleValue() - PriceActual.doubleValue()) / PriceList.doubleValue() * 100.0);
                        Discount = Util.GetValueOfDecimal(((Decimal.ToDouble(PriceList.Value) - Decimal.ToDouble(PriceActual.Value)) / Decimal.ToDouble(PriceList.Value) * 100.0));
                    }
                    if (Envs.Scale(Discount.Value) > 2)
                        // Discount = Decimal.Round(Discount.Value, 2);//, MidpointRounding.AwayFromZero);
                        Discount = Decimal.Round(Discount.Value, 2);//);//, MidpointRounding.AwayFromZero);


                    mTab.SetValue("Discount", Discount);
                }
                log.Fine("PriceEntered=" + PriceEntered + ", Actual=" + PriceActual + ", Discount=" + Discount);

                //	Check PriceLimit
                String epl = ctx.GetContext(WindowNo, "EnforcePriceLimit");
                bool enforce = ctx.IsSOTrx(WindowNo) && epl != null && epl.Equals("Y");
                bool isReturnTrx = "Y".Equals(ctx.GetContext(WindowNo, "IsReturnTrx"));
                if (enforce && (VAdvantage.Model.MRole.GetDefault().IsOverwritePriceLimit() || isReturnTrx))
                    enforce = false;
                //	Check Price Limit?
                if (enforce && Decimal.ToDouble(PriceLimit.Value) != 0.0
                  && PriceActual.Value.CompareTo(PriceLimit.Value) < 0)
                {
                    PriceActual = PriceLimit;
                    PriceEntered = (Decimal?)MUOMConversion.ConvertProductFrom(ctx, M_Product_ID,
                        C_UOM_To_ID, PriceLimit.Value);
                    if (PriceEntered == null)
                        PriceEntered = PriceLimit;
                    log.Fine("(under) PriceEntered=" + PriceEntered + ", Actual" + PriceLimit);
                    mTab.SetValue("PriceActual", PriceLimit);
                    mTab.SetValue("PriceEntered", PriceEntered);
                    //mTab.fireDataStatusEEvent("UnderLimitPrice", "", false);
                    ShowMessage.Info("UnderLimitPrice", true, "", "");
                    //	Repeat Discount calc
                    if (PriceList != 0)
                    {
                        Discount = Util.GetValueOfDecimal(((Decimal.ToDouble(PriceList.Value) - Decimal.ToDouble(PriceActual.Value)) / Decimal.ToDouble(PriceList.Value) * 100.0));
                        if (Envs.Scale(Discount.Value) > 2)
                        {
                            // Discount = Decimal.Round(Discount.Value, 2);//, MidpointRounding.AwayFromZero);
                            Discount = Decimal.Round(Discount.Value, 2);//);//, MidpointRounding.AwayFromZero);
                        }
                        mTab.SetValue("Discount", Discount);
                    }
                }

                //	Line Net Amt
                Decimal LineNetAmt = Decimal.Multiply(QtyEntered.Value, PriceActual.Value);
                if (Envs.Scale(LineNetAmt) > StdPrecision)
                    // LineNetAmt = Decimal.Round(LineNetAmt, StdPrecision);//, MidpointRounding.AwayFromZero);
                    LineNetAmt = Decimal.Round(LineNetAmt, StdPrecision);//);//, MidpointRounding.AwayFromZero);
                log.Info("LineNetAmt=" + LineNetAmt);
                mTab.SetValue("LineNetAmt", LineNetAmt);


                mTab.SetValue("GrandTotal", Decimal.Add(Util.GetValueOfDecimal(mTab.GetValue("TaxAmt")), LineNetAmt));
                //Decimal? GrandTotal = Decimal.Add(Util.GetValueOfDecimal(mTab.GetValue("TaxAmt")), LineNetAmt);


            }
            catch (Exception ex)
            {
                // MessageBox.Show("error in Amt" + ex.Message.ToString());
                //return "";
            }
            SetCalloutActive(false);
            return "";
        }

        /// <summary>
        /// Order Line - Quantity.
        /// - called from C_UOM_ID, QtyEntered, QtyEntered
        /// - enforces qty UOM relationship
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>null or error message</returns>
        public String Qty(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            if (IsCalloutActive() || value == null || value.ToString() == "" || value == DBNull.Value)
                return "";
            SetCalloutActive(true);
            try
            {
                int M_Product_ID = ctx.GetContextAsInt(WindowNo, "M_Product_ID");
                if (steps)
                {
                    log.Warning("init - M_Product_ID=" + M_Product_ID + " - ");
                }
                Decimal? QtyEntered = Envs.ZERO;
                //Decimal? QtyEntered = Envs.ZERO;
                Decimal? PriceActual, PriceEntered;

                // Check for RMA
                bool isReturnTrx = "Y".Equals(ctx.GetContext(WindowNo, "IsReturnTrx"));

                //	No Product
                if (M_Product_ID == 0)
                {
                    QtyEntered = Util.GetValueOfDecimal(mTab.GetValue("QtyEntered"));
                    QtyEntered = QtyEntered;
                    mTab.SetValue("QtyEntered", QtyEntered);
                }
                //	UOM Changed - convert from Entered -> Product
                else if (mField.GetColumnName().Equals("C_UOM_ID"))
                {
                    int C_UOM_To_ID = (int)value;
                    QtyEntered = Util.GetValueOfDecimal(mTab.GetValue("QtyEntered"));
                    // Decimal QtyEntered1 = Decimal.Round(QtyEntered.Value, MUOM.GetPrecision(ctx, C_UOM_To_ID));//, MidpointRounding.AwayFromZero);
                    Decimal QtyEntered1 = Decimal.Round(QtyEntered.Value, MUOM.GetPrecision(ctx, C_UOM_To_ID));//);//, MidpointRounding.AwayFromZero);
                    if (QtyEntered.Value.CompareTo(QtyEntered1) != 0)
                    {
                        log.Fine("Corrected QtyEntered Scale UOM=" + C_UOM_To_ID
                            + "; QtyEntered=" + QtyEntered + "->" + QtyEntered1);
                        QtyEntered = QtyEntered1;
                        mTab.SetValue("QtyEntered", QtyEntered);
                    }
                    QtyEntered = (Decimal?)MUOMConversion.ConvertProductFrom(ctx, M_Product_ID,
                        C_UOM_To_ID, QtyEntered.Value);
                    if (QtyEntered == null)
                        QtyEntered = QtyEntered;
                    bool conversion = QtyEntered.Value.CompareTo(QtyEntered.Value) != 0;
                    PriceActual = Util.GetValueOfDecimal(mTab.GetValue("PriceActual"));
                    PriceEntered = (Decimal?)MUOMConversion.ConvertProductFrom(ctx, M_Product_ID,
                        C_UOM_To_ID, PriceActual.Value);
                    if (PriceEntered == null)
                        PriceEntered = PriceActual;
                    log.Fine("UOM=" + C_UOM_To_ID
                        + ", QtyEntered/PriceActual=" + QtyEntered + "/" + PriceActual
                        + " -> " + conversion
                        + " QtyEntered/PriceEntered=" + QtyEntered + "/" + PriceEntered);
                    ctx.SetContext(WindowNo, "UOMConversion", conversion ? "Y" : "N");
                    mTab.SetValue("QtyEntered", QtyEntered);
                    mTab.SetValue("PriceEntered", PriceEntered);
                }
                //	QtyEntered changed - calculate QtyEntered
                else if (mField.GetColumnName().Equals("QtyEntered"))
                {
                    int C_UOM_To_ID = ctx.GetContextAsInt(WindowNo, "C_UOM_ID");
                    QtyEntered = Util.GetValueOfDecimal(value);
                    //Decimal? QtyEntered1 = Decimal.Round(QtyEntered.Value, MUOM.GetPrecision(ctx, C_UOM_To_ID));//, MidpointRounding.AwayFromZero);
                    Decimal? QtyEntered1 = Decimal.Round(QtyEntered.Value, MUOM.GetPrecision(ctx, C_UOM_To_ID));// MidpointRounding.AwayFromZero);
                    if (QtyEntered.Value.CompareTo(QtyEntered1.Value) != 0)
                    {
                        log.Fine("Corrected QtyEntered Scale UOM=" + C_UOM_To_ID
                            + "; QtyEntered=" + QtyEntered + "->" + QtyEntered1);
                        QtyEntered = QtyEntered1;
                        mTab.SetValue("QtyEntered", QtyEntered);
                    }
                    QtyEntered = (Decimal?)MUOMConversion.ConvertProductFrom(ctx, M_Product_ID,
                        C_UOM_To_ID, QtyEntered.Value);
                    if (QtyEntered == null)
                        QtyEntered = QtyEntered;
                    bool conversion = QtyEntered.Value.CompareTo(QtyEntered.Value) != 0;
                    log.Fine("UOM=" + C_UOM_To_ID
                        + ", QtyEntered=" + QtyEntered
                        + " -> " + conversion
                        + " QtyEntered=" + QtyEntered);
                    ctx.SetContext(WindowNo, "UOMConversion", conversion ? "Y" : "N");
                    mTab.SetValue("QtyEntered", QtyEntered);
                }
                //	QtyEntered changed - calculate QtyEntered (should not happen)
                else if (mField.GetColumnName().Equals("QtyEntered"))
                {
                    int C_UOM_To_ID = ctx.GetContextAsInt(WindowNo, "C_UOM_ID");
                    QtyEntered = Util.GetValueOfDecimal(value);
                    int precision = MProduct.Get(ctx, M_Product_ID).GetUOMPrecision();
                    //Decimal QtyEntered1 = Decimal.Round(QtyEntered.Value, precision);//, MidpointRounding.AwayFromZero);
                    Decimal QtyEntered1 = Decimal.Round(QtyEntered.Value, precision);//);//, MidpointRounding.AwayFromZero);
                    if (QtyEntered.Value.CompareTo(QtyEntered1) != 0)
                    {
                        log.Fine("Corrected QtyEntered Scale "
                            + QtyEntered + "->" + QtyEntered1);
                        QtyEntered = QtyEntered1;
                        mTab.SetValue("QtyEntered", QtyEntered);
                    }
                    QtyEntered = (Decimal?)MUOMConversion.ConvertProductTo(ctx, M_Product_ID,
                        C_UOM_To_ID, QtyEntered);
                    if (QtyEntered == null)
                        QtyEntered = QtyEntered;
                    bool conversion = QtyEntered.Value.CompareTo(QtyEntered) != 0;
                    log.Fine("UOM=" + C_UOM_To_ID
                        + ", QtyEntered=" + QtyEntered
                        + " -> " + conversion
                        + " QtyEntered=" + QtyEntered);
                    ctx.SetContext(WindowNo, "UOMConversion", conversion ? "Y" : "N");
                    mTab.SetValue("QtyEntered", QtyEntered);
                }
                else
                {
                    //	QtyEntered = (Decimal)mTab.getValue("QtyEntered");
                    QtyEntered = Util.GetValueOfDecimal(mTab.GetValue("QtyEntered"));
                }

                if (M_Product_ID != 0
                   && isReturnTrx)
                {
                    int inOutLine_ID = (int)mTab.GetValue("Orig_InOutLine_ID");
                    if (inOutLine_ID != 0)
                    {
                        MInOutLine inOutLine = new MInOutLine(ctx, inOutLine_ID, null);
                        Decimal shippedQty = inOutLine.GetMovementQty();
                        QtyEntered = Util.GetValueOfDecimal(mTab.GetValue("QtyEntered"));
                        if (shippedQty.CompareTo(QtyEntered) < 0)
                        {
                            if (ctx.IsSOTrx(WindowNo))
                            {
                                //mTab.fireDataStatusEEvent("QtyShippedLessThanQtyReturned", shippedQty.toString(), false);
                            }
                            else
                            {
                                // mTab.fireDataStatusEEvent("QtyReceivedLessThanQtyReturned", shippedQty.toString(), false);
                            }
                            mTab.SetValue("QtyEntered", shippedQty);
                            QtyEntered = shippedQty;

                            int C_UOM_To_ID = ctx.GetContextAsInt(WindowNo, "C_UOM_ID");
                            QtyEntered = (Decimal?)MUOMConversion.ConvertProductTo(ctx, M_Product_ID,
                                    C_UOM_To_ID, QtyEntered);
                            if (QtyEntered == null)
                                QtyEntered = QtyEntered;
                            mTab.SetValue("QtyEntered", QtyEntered);
                            log.Fine("QtyEntered : " + QtyEntered.ToString() +
                                        "QtyEntered : " + QtyEntered.ToString());
                        }
                    }
                }

                //	Storage
                if (M_Product_ID != 0
                    && ctx.IsSOTrx(WindowNo)
                    && QtyEntered > 0
                    && !isReturnTrx)		//	no negative (returns)
                {
                    MProduct product = MProduct.Get(ctx, M_Product_ID);
                    if (product.IsStocked())
                    {
                        int M_Warehouse_ID = ctx.GetContextAsInt(WindowNo, "M_Warehouse_ID");
                        int M_AttributeSetInstance_ID = ctx.GetContextAsInt(WindowNo, "M_AttributeSetInstance_ID");
                        Decimal? available = MStorage.GetQtyAvailable(M_Warehouse_ID, M_Product_ID, M_AttributeSetInstance_ID, null);
                        if (available == null)
                            available = Envs.ZERO;
                        if (available == 0)
                        {
                            //mTab.fireDataStatusEEvent("NoQtyAvailable", "0", false);
                        }
                        //else if (available.CompareTo(QtyEntered) < 0)
                        //{
                        //mTab.fireDataStatusEEvent("InsufficientQtyAvailable", available.toString(), false);
                        //}
                        else
                        {
                            int C_OrderLine_ID;
                            if (mTab.GetValue("C_OrderLine_ID") == DBNull.Value)
                            {
                                C_OrderLine_ID = 0;
                            }
                            else
                            {
                                C_OrderLine_ID = System.Convert.ToInt32(mTab.GetValue("C_OrderLine_ID"));
                            }
                            if (C_OrderLine_ID == null)
                                C_OrderLine_ID = 0;
                            Decimal notReserved = MOrderLine.GetNotReserved(ctx,
                                M_Warehouse_ID, M_Product_ID, M_AttributeSetInstance_ID,
                                C_OrderLine_ID);
                            if (notReserved == null)
                                notReserved = Envs.ZERO;
                            Decimal total = Decimal.Subtract(available.Value, notReserved);
                            if (total.CompareTo(QtyEntered) < 0)
                            {
                                String info = Msg.ParseTranslation(ctx, "@QtyAvailable@=" + available
                                    + "  -  @QtyNotReserved@=" + notReserved + "  =  " + total);
                                //mTab.fireDataStatusEEvent("InsufficientQtyAvailable",info, false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SetCalloutActive(false);
                // MessageBox.Show("error in Qty" + ex.Message.ToString());
                //return "";
            }
            SetCalloutActive(false);
            return "";
        }

        /// <summary>
        /// Orig_Order - Orig Order Defaults.
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>null or error message</returns>
        public String Orig_Order(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            try
            {
                if (value == DBNull.Value || value == null || value.ToString() == "")
                {
                    return "";
                }
                int C_Order_ID = System.Convert.ToInt32(value);
                if (C_Order_ID == null || C_Order_ID == 0)
                    return "";

                //	Get Details from Original Order
                MOrder order = new MOrder(ctx, C_Order_ID, null);
                MBPartner bpartner = new MBPartner(ctx, order.GetC_BPartner_ID(), null);

                // Reset Orig Shipment
                mTab.SetValue("Orig_InOut_ID", null);

                mTab.SetValue("C_BPartner_ID", order.GetC_BPartner_ID());
                mTab.SetValue("C_BPartner_Location_ID", order.GetC_BPartner_Location_ID());
                mTab.SetValue("Bill_BPartner_ID", order.GetBill_BPartner_ID());
                mTab.SetValue("Bill_Location_ID", order.GetBill_Location_ID());

                if (order.GetAD_User_ID() != 0)
                    mTab.SetValue("AD_User_ID", order.GetAD_User_ID());

                if (order.GetBill_User_ID() != 0)
                    mTab.SetValue("Bill_User_ID", order.GetBill_User_ID());

                if (ctx.IsSOTrx(WindowNo))
                    mTab.SetValue("M_ReturnPolicy_ID", bpartner.GetM_ReturnPolicy_ID());
                else
                    mTab.SetValue("M_ReturnPolicy_ID", bpartner.GetPO_ReturnPolicy_ID());

                //mTab.setValue("DateOrdered", order.getDateOrdered());
                mTab.SetValue("M_PriceList_ID", order.GetM_PriceList_ID());
                mTab.SetValue("PaymentRule", order.GetPaymentRule());
                mTab.SetValue("C_PaymentTerm_ID", order.GetC_PaymentTerm_ID());
                //mTab.setValue ("DeliveryRule", X_C_Order.DELIVERYRULE_Manual);

                mTab.SetValue("Bill_Location_ID", order.GetBill_Location_ID());
                mTab.SetValue("InvoiceRule", order.GetInvoiceRule());
                mTab.SetValue("PaymentRule", order.GetPaymentRule());
                mTab.SetValue("DeliveryViaRule", order.GetDeliveryViaRule());
                mTab.SetValue("FreightCostRule", order.GetFreightCostRule());
            }
            catch
            {
                //// MessageBox.Show("error in Orig_Order");
            }

            return "";
        }

        /// <summary>
        /// Orig_InOut - Shipment Line Defaults.
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>null or error message</returns>
        public String Orig_InOut(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            if (value == DBNull.Value || value == null || value.ToString() == "")
            {
                return "";
            }
            try
            {
                int Orig_InOut_ID = System.Convert.ToInt32(value);
                if (Orig_InOut_ID == null || Orig_InOut_ID == 0)
                    return "";

                //	Get Details from Original Shipment
                MInOut io = new MInOut(ctx, Orig_InOut_ID, null);
                mTab.SetValue("C_Project_ID", io.GetC_Project_ID());
                mTab.SetValue("C_Campaign_ID", io.GetC_Campaign_ID());
                mTab.SetValue("C_Activity_ID", io.GetC_Activity_ID());
                mTab.SetValue("AD_OrgTrx_ID", io.GetAD_OrgTrx_ID());
                mTab.SetValue("User1_ID", io.GetUser1_ID());
                mTab.SetValue("User2_ID", io.GetUser2_ID());
            }
            catch
            {
                //// MessageBox.Show("error in Orig_InOut");
            }

            return "";
        }

        /// <summary>
        /// Orig_Order - Orig Order Defaults.
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>null or error message</returns>
        public String Orig_OrderLine(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            if (value == DBNull.Value || value == null || value.ToString() == "")
            {
                return "";
            }
            try
            {
                int Orig_OrderLine_ID = System.Convert.ToInt32(value);
                if (Orig_OrderLine_ID == null || Orig_OrderLine_ID == 0)
                    return "";

                MOrderLine orderline = new MOrderLine(ctx, Orig_OrderLine_ID, null);
                mTab.SetValue("Orig_InOutLine_ID", null);
                mTab.SetValue("C_Tax_ID", orderline.GetC_Tax_ID());
                mTab.SetValue("PriceList", orderline.GetPriceList());
                mTab.SetValue("PriceLimit", orderline.GetPriceLimit());
                mTab.SetValue("PriceActual", orderline.GetPriceActual());
                mTab.SetValue("PriceEntered", orderline.GetPriceEntered());
                mTab.SetValue("C_Currency_ID", orderline.GetC_Currency_ID());
                mTab.SetValue("Discount", orderline.GetDiscount());
                mTab.SetValue("Discount", orderline.GetDiscount());
            }
            catch
            {
                //// MessageBox.Show("error in Orig_OrderLine");
            }

            return "";

        }

        /// <summary>
        /// Orig_InOutLine - Shipment Line Defaults.
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="WindowNo">current Window No</param>
        /// <param name="mTab">Grid Tab</param>
        /// <param name="mField">Grid Field</param>
        /// <param name="value">New Value</param>
        /// <returns>null or error message</returns>
        public String Orig_InOutLine(Context ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
        {
            if (value == DBNull.Value || value == null || value.ToString() == "")
            {
                return "";
            }
            try
            {
                int Orig_InOutLine_ID = System.Convert.ToInt32(value);
                if (Orig_InOutLine_ID == null || Orig_InOutLine_ID == 0)
                    return "";

                //	Get Details
                MInOutLine Orig_InOutLine = new MInOutLine(ctx, Orig_InOutLine_ID, null);

                if (Orig_InOutLine != null && Orig_InOutLine.Get_ID() != 0)
                {
                    mTab.SetValue("C_Project_ID", Orig_InOutLine.GetC_Project_ID());
                    mTab.SetValue("C_Campaign_ID", Orig_InOutLine.GetC_Campaign_ID());
                    mTab.SetValue("M_Product_ID", Orig_InOutLine.GetM_Product_ID());
                    mTab.SetValue("M_AttributeSetInstance_ID", Orig_InOutLine.GetM_AttributeSetInstance_ID());
                    mTab.SetValue("C_UOM_ID", Orig_InOutLine.GetC_UOM_ID());
                }
            }
            catch
            {
                //// MessageBox.Show("error in Orig_InOutLine");
            }
            return "";
        }
    }
}
